﻿using System;
using System.Web;
using System.Web.UI.WebControls.WebParts;
using SIMSProject.Helpers.QuickLaunch;

namespace SIMSProject.WebParts
{
    public class QuickLaunchContextWebPart : WebPart
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var returnUrl = Page.Request.QueryString["ReturnUrl"];

            if (string.IsNullOrEmpty(returnUrl))
            {
                return;
            }

            var targetVisibleContext = Page.Request.QueryString["TargetVisibleContext"];

            var context = HttpContext.Current;
            var cookie = context.Request.Cookies[QuickLaunchManager.VisibleContextCookieName];
            if (cookie != null)
            {
                context.Request.Cookies.Remove(QuickLaunchManager.VisibleContextCookieName);
                context.Response.Cookies.Remove(QuickLaunchManager.VisibleContextCookieName);
            }
            
            cookie = new HttpCookie(QuickLaunchManager.VisibleContextCookieName, targetVisibleContext)
            {
                Expires = DateTime.Now.AddMinutes(30)
            };

            context.Request.Cookies.Add(cookie);
            context.Response.Cookies.Add(cookie);

            context.Response.Redirect(returnUrl, false);
        }
    }
}